package com.leyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.entity.SpecGroup;
import com.leyou.entity.SpecParam;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.mapper.SpecGroupMapper;
import com.leyou.mapper.SpecParamMapper;
import com.leyou.service.SpecGroupService;
import com.leyou.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper,SpecGroup> implements SpecGroupService {
    @Autowired
    private SpecParamService specParamService;

    /**
     * 添加和修改规格组共用一个方法
     * @param specGroupDTO
     */
    @Override
    public void addSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        saveOrUpdate(specGroup);
    }

    @Override
    public List<SpecGroupDTO> getSpecGroupDTOSByCategoryId(Long id) {
        List<SpecGroupDTO> specGroupDTOS = SpecGroupDTO.convertEntityList(query().eq("category_id", id).list());


        List<SpecParam> specParams =
                this.specParamService.query().eq("category_id", id).list();

        //map 的key就是groupId，value为，同groupId下的所有的规格参数信息
        Map<Long, List<SpecParam>> collect =
                specParams
                        .stream()
                        .collect(
                                Collectors.groupingBy(SpecParam::getGroupId));

        specGroupDTOS.forEach(specGroupDTO -> {
            specGroupDTO.setParams(SpecParamDTO.convertEntityList(collect.get(specGroupDTO.getId())));
        });

        return specGroupDTOS;
    }

    @Override
    public List<SpecGroupDTO> getSpecGroupDTOSAndParamsByCategoryId(Long cid) {
        List<SpecGroup> specGroups = query().eq(null != cid, "category_id", cid)
                .list();

        List<SpecGroupDTO> specGroupDTOS = SpecGroupDTO.convertEntityList(specGroups);

        for (SpecGroupDTO specGroupDTO : specGroupDTOS) {
            Long groupDTOId = specGroupDTO.getId();
            List<SpecParam> specParams = specParamService.query().eq(null != cid, "category_id", cid)
                    .eq(null != groupDTOId, "id", groupDTOId)
                    .list();

            List<SpecParamDTO> specParamDTOS = SpecParamDTO.convertEntityList(specParams);
            specGroupDTO.setParams(specParamDTOS);
        }

        return specGroupDTOS;
    }
}
